package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.department.app.DepartmentService;
import crp.core.department.domain.models.DepartmentEntity;
import crp.services.api.graphql.models.DepartmentPayload;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

@ApplicationScoped
public class DepartmentFetcher {
    private final DepartmentService departmentService;

    @Inject
    public DepartmentFetcher(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    public List<DepartmentPayload> fetch(List<String> ids) {
        Map<String, DepartmentPayload> mapping = C2.map(departmentService.searcher().byIds(ids),
                DepartmentEntity::getId,
                DepartmentPayload::of);
        return C2.list(ids, mapping::get);
    }

    public <S> List<DepartmentPayload> fetch(List<S> sources, Function<S, String> idMapper) {
        Set<String> ids = C2.set(sources, idMapper, Objects::nonNull);
        Map<String, DepartmentPayload> mapping = C2.map(departmentService.searcher().byIds(ids),
                DepartmentEntity::getId,
                DepartmentPayload::of);
        return C2.list(sources, source ->
                Optional.ofNullable(idMapper.apply(source))
                        .map(mapping::get)
                        .orElse(null));
    }
}
